package com.malbbmsomanager.reports;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.malbbmsomanager.print.DM_BBM_InvoiceSalesOrder_PrintPreview;
import com.malbbmsomanagerdemo.DM_BBM_InvoiceMenu;
import com.malbbmsomanagerdemo.R;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_BBM_Sales_Summary_InvoiceWise extends Activity implements
ActionBar.OnNavigationListener{

	private static final String TAG = null;
	// Database Name.
	private static final String DATABASE_NAME = "dminvoicemanagerbbm.db";
	// ****Main Transaction Table****
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0",
			item_result_7 = "0", item_result_8 = "0", item_result_9 = "0",
			item_result_13 = "0", item_result_10, PrintGrandTot;

	int item_result_tot_2 = 0, item_result_tot_3 = 0, item_result_tot_4 = 0,
			item_result_tot_5 = 0, item_result_tot_6 = 0,
			item_result_tot_7 = 0, item_result_tot_8 = 0,
			item_result_tot_9 = 0, PrintGrandTot_tot = 0;
	double item_result_tot_10 = 0.0, item_result_tot_13 = 0.0;
	int ItemsFreeQty = 0;
	int toDayTag = 0;
	DecimalFormat numberFormat = new DecimalFormat("#.000000");
	DecimalFormat numberFormatAmt = new DecimalFormat("#,###,###.00");
	
	//DateDiscountValue,DateTaxValue,DateSalesOrdValue
	BigDecimal DateDiscountValue = new BigDecimal("0.00");
	BigDecimal DateTaxValue = new BigDecimal("0.00");
	BigDecimal DateSalesOrdValue = new BigDecimal("0.00");
	//TotalDiscountValue,TotalTaxValue,TotalSalesOrdValue
	BigDecimal TotalDiscountValue = new BigDecimal("0.00");
	BigDecimal TotalTaxValue = new BigDecimal("0.00");
	BigDecimal TotalSalesOrdValue = new BigDecimal("0.00");

	EditText dmreportfromdate, dmreporttodate, dmdisplayrepname;
	TextView txtHeadingReports, totalSum, totalTonage, fcontrollname;
	TextView recordtot_1, recordtot_2, recordtot_3, recordtot_4, recordtot_5,
			recordtot_6, recordtot_7, recordtot_8, recordtot_9, recordtot_10,
			recordtot_11, recordtot_12;

	String currentReportName, selectFromDate, selectToDate, currentUserTemp,
			currentUserPrefix, UserLocCode, selectFromDateNow, selectToDateNow;

	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
	Date date, LoadingFromDate, LoadingToDate, LoadingOriDate;
	private ActionBar actionBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_sales_summary_datewise);

		fcontrollname = (TextView) findViewById(R.id.fcontrollname);
		fcontrollname.setText("Sales Summary InvoiceWise Report");
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			selectFromDate = extras.getString("FromDate");
			selectToDate = extras.getString("ToDate");
		}
		
		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);
		
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_0", "item_result_1",
				"item_result_2", "item_result_3", "item_result_4",
				"item_result_5", "item_result_6", "item_result_7",
				"item_result_8", "item_result_9", "item_result_10" };

		int[] totrdes = new int[] { R.id.record_0, R.id.record_1,
				R.id.record_2, R.id.record_3, R.id.record_4, R.id.record_5,
				R.id.record_6, R.id.record_7, R.id.record_8, R.id.record_9,
				R.id.record_10 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String query;
		query = "SELECT * FROM FOrdDet GROUP BY RefNo";
		// ***Select sum queries need seperately 8 to for the combinations
		allrowitemsdes = mydb.rawQuery(query, null);
		Log.v(TAG, "Count:" + allrowitemsdes.getCount());
		String PreTxnDate = "000";
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					
					String ParentTxnDate = allrowitemsdes.getString(2);
					String ParentRefNo = allrowitemsdes.getString(1);
					try {
						LoadingFromDate = targetFormat.parse(selectFromDate);
						LoadingToDate = targetFormat.parse(selectToDate);
						LoadingOriDate = targetFormat.parse(ParentTxnDate);
					} catch (ParseException ex) {
						Log.v("", "ParseException :"+ ex);
					}
					
					if ((LoadingOriDate.after(LoadingFromDate) && LoadingOriDate.before(LoadingToDate)) ||(LoadingOriDate.equals(LoadingFromDate) || LoadingOriDate.equals(LoadingToDate))) {
						Cursor displaySummary = null;
						String querySummary;
						
						querySummary = "SELECT * FROM FOrdDet Where RefNo = '"+ ParentRefNo +"'";
						displaySummary = mydb.rawQuery(querySummary, null);
						
						if (displaySummary != null) {
							if (displaySummary.getCount() > 0) {
								while (displaySummary.moveToNext()) {
									String RefNo = displaySummary.getString(1);
									String TxnDate = displaySummary.getString(2);
									String Itemcode = displaySummary.getString(5);
									String Quantity = displaySummary.getString(6);
									String SalesPrice = displaySummary.getString(10);
									String Discount = displaySummary.getString(16);
									String Tax = displaySummary.getString(20);
									String Packing = displaySummary.getString(28);
									String freeqty = displaySummary.getString(31);
									String ItemName = displaySummary.getString(33);
									String BrandName = displaySummary.getString(36);
									String Value = displaySummary.getString(37);
									
									try{
										ItemsFreeQty = Integer.parseInt(freeqty);
									}
									catch(Exception e){
										ItemsFreeQty = 0;
									}
									if(ItemsFreeQty <= 0){
										BigDecimal DiscountValue = new BigDecimal(Discount.replaceAll("[,]", ""));
										BigDecimal TaxValue = new BigDecimal(Tax.replaceAll("[,]", ""));
										BigDecimal SalesOrdValue = new BigDecimal(Value.replaceAll("[,]", ""));
										
										DateDiscountValue = DateDiscountValue.add(DiscountValue);
										DateTaxValue = DateTaxValue.add(TaxValue);
										DateSalesOrdValue = DateSalesOrdValue.add(SalesOrdValue);
										
										
										HashMap<String, String> maptrdes = new HashMap<String, String>();
										maptrdes.put("item_result_0", TxnDate);
										maptrdes.put("item_result_1", RefNo);
										maptrdes.put("item_result_2", Itemcode);
										maptrdes.put("item_result_3", ItemName);
										maptrdes.put("item_result_4", Packing);
										maptrdes.put("item_result_5", BrandName);
										maptrdes.put("item_result_6", Quantity);
										maptrdes.put("item_result_7", SalesPrice);
										maptrdes.put("item_result_8", Discount);
										maptrdes.put("item_result_9", Tax);
										maptrdes.put("item_result_10", Value);
										maptrdes.put("item_result_11", TxnDate);
										
										// fill in the grid_item layout
										fillMapstrdes.add(maptrdes);
										SimpleAdapter adaptertrdes = new SimpleAdapter(this,
												fillMapstrdes,
												R.layout.dm_bbm_sales_summary_datewise_raw,
												fromtrdes, totrdes);
										lvtypedes.setAdapter(adaptertrdes);
									}
									
								}
							}
						}
						//Display Current Date Summary
						
						DateDiscountValue = DateDiscountValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
						DateTaxValue = DateTaxValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
						DateSalesOrdValue = DateSalesOrdValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
						
						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("item_result_0", "");
						maptrdes.put("item_result_1", "");
						maptrdes.put("item_result_2", "");
						maptrdes.put("item_result_3", "Ref No :" + ParentRefNo);
						maptrdes.put("item_result_4", "");
						maptrdes.put("item_result_5", "");
						maptrdes.put("item_result_6", "Total");
						maptrdes.put("item_result_7", "");
						maptrdes.put("item_result_8", ""+DateDiscountValue);
						maptrdes.put("item_result_9", ""+DateTaxValue);
						maptrdes.put("item_result_10", ""+DateSalesOrdValue);
						maptrdes.put("item_result_11", "");
						
						// fill in the grid_item layout
						fillMapstrdes.add(maptrdes);
						SimpleAdapter adaptertrdes = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_bbm_sales_summary_datewise_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdes);
						
						//TotalDiscountValue,TotalTaxValue,TotalSalesOrdValue
						TotalDiscountValue = TotalDiscountValue.add(DateDiscountValue);
						TotalTaxValue = TotalTaxValue.add(DateTaxValue);
						TotalSalesOrdValue = TotalSalesOrdValue.add(DateSalesOrdValue);
						
						DateDiscountValue = new BigDecimal("0.00");
						DateTaxValue = new BigDecimal("0.00");
						DateSalesOrdValue = new BigDecimal("0.00");
						
					}
					else{
						Log.v("", "INVALID DATE :" + "From :" + selectFromDate + " To :" + selectToDate + "Selected : " +ParentTxnDate);
					}
				}
			}
		}
       /************Display Report Summary*********************/
		
		TotalDiscountValue = TotalDiscountValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		TotalTaxValue = TotalTaxValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		TotalSalesOrdValue = TotalSalesOrdValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		
		HashMap<String, String> maptrdes = new HashMap<String, String>();
		maptrdes.put("item_result_0", "");
		maptrdes.put("item_result_1", "");
		maptrdes.put("item_result_2", "");
		maptrdes.put("item_result_3", "");
		maptrdes.put("item_result_4", "");
		maptrdes.put("item_result_5", "");
		maptrdes.put("item_result_6", "Grand Total");
		maptrdes.put("item_result_7", "");
		maptrdes.put("item_result_8", ""+TotalDiscountValue);
		maptrdes.put("item_result_9", ""+TotalTaxValue);
		maptrdes.put("item_result_10", ""+TotalSalesOrdValue);
		maptrdes.put("item_result_11", "");
		
		// fill in the grid_item layout
		fillMapstrdes.add(maptrdes);
		SimpleAdapter adaptertrdes = new SimpleAdapter(this,
				fillMapstrdes,
				R.layout.dm_bbm_sales_summary_datewise_raw,
				fromtrdes, totrdes);
		lvtypedes.setAdapter(adaptertrdes);
	}
	
	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		onBackPressed();
		DM_BBM_Sales_Summary_InvoiceWise.this.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		/*Intent myIntent = new Intent(DM_BBM_Sales_Summary_InvoiceWise.this,
				DM_BBM_Reports_Generator.class);
		myIntent.putExtra("TAGID", "0/SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;*/
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}
}
